<?php
namespace app\common\model\newmodel;

use think\Model;
use app\common\model\newmodel\UserFactory;
use app\common\model\newmodel\User;
use app\common\model\newmodel\UserAgency;
use app\common\model\newmodel\Accessories;
use app\common\model\newmodel\Device;
use app\common\model\newmodel\Customer;
use think\Db;

class ContractOrder extends Model
{
    protected $table = 'contract_order';
    protected $pk = 'id';

    public function devices()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Device', 'device_id', 'id')->field('id,device_name');
    }

    public function contract()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Contract', 'contract_id', 'id')->field('id,contract_name,img_url,recipient_name,recipient_tel,recipient_address');
;
    }

    public function customer()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Customer', 'customer_id', 'CustomerId')->field('CustomerId,Address,UserName,Tel');
    }

    public function factory()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Factory', 'factory_id', 'id');
    }

    /**
     * 拆单（生成订单
     */
    public static function createProductOrders($data)
    {
        $orderData=Db::name('contract_order')->where('State',1)->where('contract_id',$data['contract_id'])->select();
        if($orderData){
            return ['code' =>0,'msg' =>'该合同已经生成订单，如果要重新生成，请先删除原来的订单'];
        }
        if (empty($data['contract_id']) || empty($data['devices_id']) || empty($data['accessories_id']) || empty($data['customer_id'])) {
            return ['code' => 0, 'msg' => '参数不完整'];
        }
        $devices_id = is_array($data['devices_id']) ? $data['devices_id'] : explode(',', $data['devices_id']);
        $accessories_id = is_array($data['accessories_id']) ? $data['accessories_id'] : explode(',', $data['accessories_id']);

        $devices = Device::where('id', 'in', $devices_id)->select();
        $deviceIds = array_column($devices->toArray(), 'id');
        $invalidIds = array_diff($devices_id, $deviceIds);
        if (!empty($invalidIds)) {
            return ['code' => 0, 'msg' => '设备ID不存在：' . implode(',', $invalidIds)];
        }

        $accessories = Accessories::where('id', 'in', $accessories_id)->select();
        $deviceAccessoriesMap = [];
        foreach ($accessories as $accessory) {
            $deviceId = $accessory['device_id'];
            $deviceAccessoriesMap[$deviceId][] = $accessory['id'];
        }

        // 生成流量卡订单
        $cardCount = Device::where('id', 'in', $devices_id)->where('is_need', 1)->count();
        $cardOrder = new self();
        $cardOrder->contract_id = $data['contract_id'];
        $cardOrder->customer_id = $data['customer_id'];
        $cardOrder->accessories_id = 1;
        $cardOrder->device_id = 1;
        $cardOrder->factory_id = 1;
        $cardOrder->status = 1;
        $cardOrder->create_time = time();
        $cardOrder->update_time = time();
        $cardOrder->remark = $cardCount . '张';
        $cardOrder->save();
        $cardOrderId = $cardOrder->id;

        $currentTime = time();
        $orderIds = [];
        self::startTrans();
        try {
            foreach ($devices as $device) {
                $deviceId = $device['id'];
                $factoryId = $device['factory_id'];
                $accessoryIds = $deviceAccessoriesMap[$deviceId] ?? [];
                $order = new self();
                $order->contract_id = $data['contract_id'];
                $order->device_id = $deviceId;
                $order->accessories_id = !empty($accessoryIds) ? implode(',', $accessoryIds) : '';
                $order->factory_id = $factoryId;
                $order->customer_id = $data['customer_id'];
                $order->track_number = $data['track_number'] ?? '';
                $order->status = 1;
                $order->create_time = $currentTime;
                $order->update_time = $currentTime;
                $order->save();
                $orderIds[] = $order->id;
            }
            array_unshift($orderIds, $cardOrderId);
            self::commit();
            return [
                'code' => 1,
                'msg' => '生成订单成功',
                'order_ids' => $orderIds,
                'order_count' => count($orderIds)
            ];
        } catch (\Exception $e) {
            self::rollback();
            return ['code' => 0, 'msg' => '生成订单失败：' . $e->getMessage()];
        }
    }


    /**
     * 订单列表（多角色，工厂订单按工厂ID区分）
     */
    public static function getOrderList($userId, $page = 1, $pageSize = 10, $keyword = '', $status='')
    {
        $user = User::get($userId);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在'];
        }
        $role = $user->Role;
        $query = self::with(['devices','contract', 'customer', 'factory']);

        // 工厂管理员/员工
        if (in_array($role, [301, 302])) {
    
            $factoryId = UserFactory::getFactoryIdByUserId($userId);
            if (!$factoryId) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('factory_id', $factoryId);
        }
        // 代理商管理员
        elseif ($role == 401) {
            $agencyId = UserAgency::getAgencyIdByUserId($userId);
            if (!$agencyId) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $agencyUserIds = UserAgency::getUserIdsByAgencyId($agencyId);
            $customerIds = Customer::where('AgentId', 'in', $agencyUserIds)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 代理商员工
        elseif ($role == 402) {
            $customerIds = Customer::where('AgentId', $userId)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' =>''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 业务员
        elseif ($role == 201) {
            // 业务员只能看非代理商客户的订单
            $customerIds = Customer::where('IsAgent', 0)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 其它角色无权限
        else {
            return ['code' => 0, 'msg' => '无权限'];
        }

        if (!empty($keyword)) {
            $query = $query->where('track_number', 'like', "%{$keyword}%");
        }
        if (!empty($status)) {
            $query = $query->where('status',$status);
        }

        $list = $query->order('create_time desc')
                ->where('State',1)
                ->paginate([
                    'list_rows' => $pageSize,
                    'page' => $page,
                ]);

        $items = $list->toArray();

        // 处理配件信息
        if (!empty($items['data'])) {
            foreach ($items['data'] as &$item) {
                $accessoryIds = array_filter(explode(',', $item['accessories_id'] ?? ''));
                $accessories = [];
                if ($accessoryIds) {
                    $accessories = Accessories::where('id', 'in', $accessoryIds)
                        ->field('id, accessory_name')
                        ->select()
                        ->toArray();
                }
                $item['accessories'] = $accessories;
                unset($item['device_id']);
                unset($item['accessories_id']);
                unset($item['factory_id']);
                unset($item['contract_id']);
                unset($item['customer_id']);
            }
            unset($item); 
        }

        return [
            'code' => 1,
            'msg' => 'success',
            'data' => $items 
        ];
    }

    /**
     * 订单状态修改
     */
    public static function updateOrderStatus($data)
    {
        if (empty($data['id'])) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }
        $orderId=$data['id'];
        $order = self::get($orderId);
        if (!$order) {
            return ['code' => 0, 'msg' => '订单不存在'];
        }
        
        $order->track_number =$data['track_number'] ?? '';
        $order->status = $data['status'] ?? '';
        $order->update_time = time();
        $order->remark=$data['remark'] ?? '';
        $order->save();
        return ['code' => 1, 'msg' => '修改成功'];
    }

    /**
     * 根据合同ID获取订单详情
     */
    public static function getOrdersByContractId($contract_id)
    {
        if(empty($contract_id)){
            return ['code' =>0,'msg' => '参数不完整'];
        }
        $query= self::with(['devices','factory'])->where('State',1)->where('contract_id',$contract_id)->select()->toArray();
        if ($query) {
            foreach ($query as &$item) {
                $accessoryIds = array_filter(explode(',', $item['accessories_id'] ?? ''));
                $accessories = [];
                if ($accessoryIds) {
                    $accessories = Accessories::where('id', 'in', $accessoryIds)
                        ->field('id, accessory_name')
                        ->select()
                        ->toArray();
                }
                $item['accessories'] = $accessories;
                unset($item['device_id']);
                unset($item['accessories_id']);
                unset($item['factory_id']);
                unset($item['contract_id']);
                unset($item['customer_id']);
            }
            unset($item); 
        }else{
            return ['code'=>0,'msg'=>'暂无订单信息'];
        }
        return [
            'code' => 1,
            'msg' => 'success',
            'data' => $query 
        ];
        
    }


    /*
    public static function getOrderList($userId, $page = 1, $pageSize = 10, $keyword = '')
    {
        $user = User::get($userId);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在'];
        }
        $role = $user->Role;
        $query = self::with(['devices','contract', 'customer', 'factory']);

        // 工厂管理员/员工
        if (in_array($role, [301, 302])) {
            // 工厂ID
            $factoryId = UserFactory::getFactoryIdByUserId($userId);
            if (!$factoryId) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('factory_id', $factoryId);
        }
        // 代理商管理员
        elseif ($role == 303) {
            $agencyId = UserAgency::getAgencyIdByUserId($userId);
            if (!$agencyId) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $agencyUserIds = UserAgency::getUserIdsByAgencyId($agencyId);
            $customerIds = Customer::where('AgentId', 'in', $agencyUserIds)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 代理商员工
        elseif ($role == 304) {
            $customerIds = Customer::where('AgentId', $userId)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' =>''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 业务员
        elseif ($role == 201) {
            // 业务员只能看非代理商客户的订单
            $customerIds = Customer::where('IsAgent', 0)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 其它角色无权限
        else {
            return ['code' => 0, 'msg' => '无权限'];
        }

        // 物流单号关键词搜索
        if (!empty($keyword)) {
            $query = $query->where('track_number', 'like', "%{$keyword}%");
        }

        $list = $query->order('create_time desc')
        ->paginate([
            'list_rows' => $pageSize,
            'page' => $page,
        ]);

        return [
            'code' => 1,
            'msg' => 'success',
            'data' => $list
        ];
    }
     */
   
}